package com.xiao.examples;

import androidx.appcompat.app.AppCompatActivity;

import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageInstaller;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initUI();

        testInLog();
    }

    /**
     * 多个按钮监听采用switch-case语句
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_install:
                installApk();
                break;
        }
    }

    private void initUI() {
        Button btnInstall =findViewById(R.id.btn_install);
        btnInstall.setOnClickListener(this);
    }

    private void installApk() {
        // 请求授予 安装未知来源应用 权限
        boolean bCanInstall = getPackageManager().canRequestPackageInstalls();
        if (!bCanInstall) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
            return;
        }

        try {
            // 安装
            File apkFile = new File("install_test.apk");
            if (!apkFile.exists()) {
                Toast.makeText(this, apkFile.getName()+ " 不存在", Toast.LENGTH_LONG).show();
                return;
            }

            PackageInstaller packageInstaller = getPackageManager().getPackageInstaller();

            // 定义安装请求
            PackageInstaller.SessionParams sessionParams = new PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL);
            int sessionId = packageInstaller.createSession(sessionParams);

            PackageInstaller.Session session = packageInstaller.openSession(sessionId);
            OutputStream out = session.openWrite("my_app", 0, -1);
            FileInputStream in = new FileInputStream(apkFile);

            byte[] buffer = new byte[65536];
            int length;
            while ((length = in.read(buffer)) != -1) {
                out.write(buffer, 0, length);
            }
            session.fsync(out);

            // 提交安装请求
            session.commit(createIntentSender(sessionId));

            session.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Toast.makeText(this, "安装...", Toast.LENGTH_SHORT).show();
    }

    // 创建 Intent 启动安装
    private IntentSender createIntentSender(int sessionId) {
        Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
        intent.setDataAndType(Uri.fromFile(new File("install_test.apk")), "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        return pendingIntent.getIntentSender();
    }

    private void testInLog() {
        SystemUtil.showSystemParameter(this, this);
    }
}